
import 'package:erp/Entity/Customer.dart';
import 'package:erp/Entity/CustomerType.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/CustomerStore.dart';
import 'package:erp/Store/CustomerTypeStore.dart';
import 'package:erp/UI/CodeResources/Localization.dart';
import 'package:erp/UI/Components/EmbeddableStatefulWidget.dart';
import 'package:erp/UI/Components/EventfulState.dart';
import 'package:erp/UI/Components/LogoScaffold.dart';
import 'package:erp/UI/Components/MessageDialog.dart';
import 'package:erp/UI/Components/QuestionDialog.dart';
import 'package:erp/UI/Pages/BasicInformationManagementPages/CustomerTypePage/CustomerTypePage.dart';
import 'package:erp/global.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class CustomerPage extends StatefulWidget {
  bool isSelectionMode;

  CustomerPage({this.isSelectionMode = false});

  @override
  State<StatefulWidget> createState() => CustomerPageState();
}

class CustomerPageState extends EventfulState<CustomerPage> {

  @override
  void initState() {
    eventIds = [
      globalBus.subscribe(Events.CUSTOMER_SELECT_SUCCESS, (bus, data){setState(() {});}),
      globalBus.subscribe(Events.CUSTOMER_INSERT_SUCCESS, (bus, data){setState(() {});}),
      globalBus.subscribe(Events.CUSTOMER_UPDATE_SUCCESS, (bus, data){setState(() {});}),
      globalBus.subscribe(Events.CUSTOMER_DELETE_SUCCESS, (bus, data){setState(() {});}),

      globalBus.subscribe(Events.CUSTOMER_SELECT_ERROR, (bus, exception)async {
        await showMessageDialog(context, title: "ئوقۇش جەريانىدا خاتالىق يۈز بەردى", content: exception.toString());
      }),
      globalBus.subscribe(Events.CUSTOMER_INSERT_ERROR, (bus, exception)async {
        await showMessageDialog(context, title: "قوشۇش جەريانىدا خاتالىق يۈز بەردى", content: exception.toString());
      }),
      globalBus.subscribe(Events.CUSTOMER_UPDATE_ERROR, (bus, exception)async {
        await showMessageDialog(context, title: "يىڭىلاش جەريانىدا خاتالىق يۈز بەردى", content: exception.toString());
      }),
      globalBus.subscribe(Events.CUSTOMER_DELETE_ERROR, (bus, exception)async {
        await showMessageDialog(context, title: "ئۆچۈرۈش جەريانىدا خاتالىق يۈز بەردى", content: exception.toString());
      })
    ];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return LogoScaffold(
      title: "خىرىدار ئۇچۇرى",
      assetsLogoName: "assets/pictures/salesman.png",
      heroName: "CustomerHero",
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () async {
          var customer = Customer();
          var isOkay = await showEditDialog(context, customer);
          if (isOkay) globalBus.publish(Events.CUSTOMER_INSERT_REQUEST, customer);
        },
      ),
      contentDelegate: SliverChildListDelegate(CustomerStore.customers.map((customer) => buildListItem(customer)).toList()),
    );
  }

  Widget buildListItem(Customer customer){
    return ListTile(
      title: Text(customer.name),
      subtitle: Text(customer.phone),
      leading: Image.asset("assets/pictures/salesman.png", width: 40.0, height: 40.0,),
      trailing: Wrap(
        children: <Widget>[
          IconButton(
              icon: Icon(Icons.edit),
              onPressed: () async {
                var data = Customer.fromJson(customer.toJson());
                var isOkay = await showEditDialog(context, data);
                if (isOkay) globalBus.publish(Events.CUSTOMER_UPDATE_REQUEST, data);
              }
          ),
          IconButton(
              icon: Icon(Icons.delete_forever),
              onPressed: ()async {
                var isOkay = await showQuestionDialog(context, title: "ئەسكەرتىش", content: "نۆۋەتتىكى خىرىدارنى ئۆچۈرمەكچى بولۇۋاتىسىز، راستىنلا ئۆچۈرەمسىز؟") ?? false;
                if (isOkay) globalBus.publish(Events.CUSTOMER_DELETE_REQUEST, customer);
              }
          )
        ],
      ),
      onTap: (){
        if (widget.isSelectionMode) Navigator.of(context).pop(customer);
      },
    );
  }

  Future<bool> showEditDialog(BuildContext context, Customer customer) async {
    CustomerType customerType = CustomerTypeStore.customerTypes.singleWhere((item) => item.id == customer.type, orElse: () => null);
    var currentLocale = AppLocalizations.of(context);

    var nameController = TextEditingController(text: customer.name ?? "");
    var phoneController = TextEditingController(text: customer.phone ?? "");
    var memoController = TextEditingController(text: customer.memo ?? "");
    return await showDialog(context: context, barrierDismissible: false, builder: (context) => Directionality(
        textDirection: currentLocale.textDirection,
        child: EmbeddedWidget(
          initEvent: (state){

          },
          widgetBuilder: (context, state) => AlertDialog(
            title: Text("خىرىدار ئۇچۇرى"),
            content: Container(
              width: 350.0,
              child: Wrap(
                children: <Widget>[
                  TextField(
                    controller: nameController,
                    decoration: InputDecoration(
                      labelText: "ئىسمى",
                      hintText: "خىرىدار ئىسمىنى كىرگۈزۈڭ"
                    ),
                  ),
                  TextField(
                    controller: phoneController,
                    decoration: InputDecoration(
                      labelText: "تېلېفون نومۇرى",
                      hintText: "تېلېفون نومۇرىنى كىرگۈزۈڭ"
                    ),
                    keyboardType: TextInputType.numberWithOptions(
                      signed: true,
                      decimal: false
                    ),
                  ),
                  TextField(
                    controller: memoController,
                    decoration: InputDecoration(
                      labelText: "ئىزاھات",
                      hintText: "ئىزاھاتى بولسا يىزىپ قويسىڭىز بولىدۇ"
                    ),
                  ),
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: Text("خىرىدار تۈرى: "),
                      ),
                      RaisedButton(
                        child: Text(customerType?.name ?? "چىكىپ تۈر تاللاڭ"),
                        onPressed: ()async {
                          customerType = await Navigator.of(context).push<CustomerType>(MaterialPageRoute(builder: (context) => CustomerTypePage(isSelectionMode: true)));
                          state.setState((){});
                        },
                      )
                    ],
                  )
                ],
              ),
            ),
            actions: <Widget>[
              FlatButton(
                  onPressed: () async {
                    var valid = true;
                    valid &= customerType != null;
                    if (!valid){
                      await showMessageDialog(context, title: "ئەسكەرتىش", content: "خىرىدار تۈرىنى تاللاڭ");
                      return;
                    }
                    valid &= nameController.text.isNotEmpty;
                    if (!valid){
                      await showMessageDialog(context, title: "ئەسكەرتىش", content: "خىرىدار ئىسمىنى كىرگۈزۈڭ");
                      return;
                    }
                    valid &= phoneController.text.isNotEmpty;
                    if (!valid) {
                      await showMessageDialog(context, title: "ئەسكەرتىش", content: "تېلېفون نومۇرىنى كىرگۈزۈڭ");
                      return;
                    }
                    customer
                    ..name = nameController.text
                    ..type = customerType.id
                    ..phone = phoneController.text
                    ..memo = memoController.text;

                    Navigator.of(context).pop(true);
                  },
                  child: Text("جەزىملەشتۈرۈش")
              ),
              FlatButton(
                  onPressed: (){
                    Navigator.of(context).pop(false);
                  },
                  child: Text("بىكار قىلىش")
              ),
            ],
          )
        )
    )) ?? false;
  }
}